package com.wisdom.system.api.core.oauth;

import com.wisdom.system.entity.current.CurrentUser;
import com.wisdom.system.common.exception.LogicException;
import com.wisdom.system.service.current.CurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private CurrentUserService currentUserService;

    @Override
    public UserDetails loadUserByUsername(String loginCode) throws UsernameNotFoundException {
        CurrentUser currentUser = currentUserService.getCurrentUser(loginCode);
        if (currentUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //todo 判断用户是否状态为0
        if (currentUser.getState() == 0){
             throw LogicException.of("该用户已经被禁用，请联系管理员！");
        }
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("user"));
        return new User(currentUser.getLoginCode(), currentUser.getPassword(), authorities);
    }
}
